package gw.demo2.controller;

import gw.demo2.entity.Admin;
import gw.demo2.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;

    @PostMapping("/login")
    public ResponseEntity<?> adminLogin(@RequestBody Map<String, Object> request) {
        int adminId = Integer.parseInt(request.get("adminId").toString());
        String password = request.get("password").toString();

        Admin admin = adminService.login(adminId, password);
        if (admin != null) {
            return ResponseEntity.ok().body(admin);
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid credentials");
        }
    }

    @GetMapping("/counts")
    public ResponseEntity<?> getCounts() {
        return ResponseEntity.ok().body(adminService.getCounts());
    }

    @GetMapping("/purchase-records")
    public ResponseEntity<?> getPurchaseRecords() {
        return ResponseEntity.ok().body(adminService.getPurchaseRecords());
    }

    @DeleteMapping("/users/{userId}")
    public ResponseEntity<?> deleteUser(@PathVariable int userId) {
        if (adminService.deleteUser(userId)) {
            return ResponseEntity.ok().body("User deleted successfully");
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found");
        }
    }
    @GetMapping("/users")
    public ResponseEntity<?> getAllUsers() {
        return ResponseEntity.ok().body(adminService.getAllUsers());
    }

    @GetMapping("/merchants")
    public ResponseEntity<?> getAllMerchants() {
        return ResponseEntity.ok().body(adminService.getAllMerchants());
    }

    @DeleteMapping("/merchants/{merchantId}")
    public ResponseEntity<?> deleteMerchant(@PathVariable int merchantId) {
        if (adminService.deleteMerchant(merchantId)) {
            return ResponseEntity.ok().body("Merchant deleted successfully");
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Merchant not found");
        }
    }

    @PutMapping("/password")
    public ResponseEntity<?> updatePassword(@RequestBody Map<String, Object> request) {
        int adminId = Integer.parseInt(request.get("adminId").toString());
        String newPassword = request.get("newPassword").toString();

        if (adminService.updateAdminPassword(adminId, newPassword)) {
            return ResponseEntity.ok().body("Password updated successfully");
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Admin not found");
        }
    }
}